using UnityEngine;

public class MoveComp : MonoBehaviour
{
    private Animator _animator;
    private CharacterController _controller;
    private Transform _cameraTransform;
    private PlayerAttributeComp _attributeComp;


    [Header("玩家转向速度")] public float turnSmoothTime = 0.1f;

    private float _turnSmoothVelocity;

    // [Header("玩家移速")] public float speed = 6f;
    [Header("玩家移动加速度")] private float _currentSpeed;
    public float speedSmoothTime = 0.3f;
    private float _speedSmoothVelocity;

    private const string SpeedAnimKey = "speed";

    private void Awake()
    {
        _animator = GetComponent<Animator>();
        _controller = GetComponent<CharacterController>();
        _attributeComp = GetComponent<PlayerAttributeComp>();
        _cameraTransform = Camera.main.transform;
    }

    void Update()
    {
        // 输入移动
        HandleMove();
    }

    private void HandleMove()
    {
        // 获取输入
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

        if (direction.magnitude >= 0.1f)
        {
            // 计算目标角度
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + _cameraTransform.eulerAngles.y;
            // 平滑转向a
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref _turnSmoothVelocity,
                turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);
            // 计算移动方向
            Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;

            // 移动角色
            // 平滑移动速度
            _currentSpeed = Mathf.SmoothDamp(_currentSpeed,
                _attributeComp.GetAttributeValue(AttributeType.Speed), ref _speedSmoothVelocity,
                speedSmoothTime);
            _animator.SetFloat(SpeedAnimKey, _currentSpeed);
            _controller.Move(moveDir.normalized * _currentSpeed * Time.deltaTime);
        }
        else
        {
            _animator.SetFloat(SpeedAnimKey, 0f);
            _currentSpeed = 0f;
        }
    }
}